<template>
  <div>
    <el-form :inline="true">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="名称">
            <el-input v-model="queryParam.Name" @keyup.enter.native="research" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="text-align: center">
        <el-button type="warning" round @click="research">
          查询
        </el-button>
      </el-row>
    </el-form>

    <el-row style="margin-top: 20px">
      <el-button type="primary" @click="toAdd">
        添加
      </el-button>
      <el-button type="primary" @click="toDownloadTemplate">
        下载导入模板
      </el-button>
      <el-button type="primary" @click="toImport">
        导入
      </el-button>
    </el-row>

    <el-table
      :data="data"
      border
      fit
      :height="tableHeight"
      size="small"
      highlight-current-row
      style="width: 100%; margin-top: 20px"
      @sort-change="sortChange"
    >
      <el-table-column sortable="custom" label="属性值" prop="Name" />
      <el-table-column sortable="custom" label="值" prop="Value" />
      <el-table-column sortable="custom" label="前端展示名称" prop="Remarks" />
      <el-table-column sortable="custom" prop="CreatedAt" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.CreatedAt | parseDate }}
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="UpdatedAt" label="修改时间">
        <template slot-scope="scope">
          {{ scope.row.UpdatedAt | parseDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="toEdit(scope.row)">
            修改
          </el-button>
          <el-button type="text" @click="toDel(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 10px">
      <el-col :span="24">
        <el-pagination
          v-show="TotalRecord>0"
          :current-page="queryParam.CurrentPage"
          :page-sizes="[10,20,30, 50]"
          :page-size="queryParam.PageSize"
          :total="TotalRecord"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <el-dialog :visible.sync="importDictDialog.show" :close-on-click-modal="false">
      <el-form>
        <el-form-item label="文件">
          <el-upload :http-request="handleCsvInput" action="" accept=".csv" :show-file-list="false">
            <el-button type="primary">
              选择文件
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import apolloClient from '@/utils/graphql'
import gql from 'graphql-tag'
import csvParse from 'csv-parse/lib/sync'
import { Loading } from 'element-ui'
export default {
  name: 'DictPage',
  components: {

  },
  props: {
    dictCategoryId: {
      type: String
    }
  },
  data() {
    return {
      queryParam: {
        CurrentPage: 1,
        PageSize: 20,
        Name: null,
        DictCategoryId: this.dictCategoryId,
        OrderBy: '',
        OrderColumn: ''
      },
      data: [],
      TotalRecord: 0,
      currentRow: '',
      importDictDialog: {
        show: false,
        filePath: null
      }
    }
  },
  computed: {
    // 返回当前列的数据
    currentData() {
      if (this.currentRow === '' || this.currentRow === undefined || this.currentRow == null) {
        return {}
      }
      return this.data[this.currentRow]
    },
    tableHeight() {
      return document.body.clientHeight - 300
    }
  },
  mounted() {
    this.search()
  },
  methods: {
    sortChange(column) {
      this.queryParam.OrderBy = column.order
      this.queryParam.OrderColumn = column.prop
      this.research()
    },
    handleCsvInput(option) {
      var that = this
      console.log(option)
      var fileReader = new FileReader()
      fileReader.readAsText(option.file, 'gb2312')
      fileReader.onload = async function() {
        var result = fileReader.result
        console.log(result)
        var records = csvParse(result, {
          skip_empty_lines: true
        })
        if (!records || records.length === 0) {
          this.$notify.error('导入内容为空')
          return
        }
        const loading = Loading.service()
        for (let i = 1; i < records.length; i++) {
          var record = records[i]
          var postData = {}
          postData.Name = record[0]
          postData.Value = record[1]
          postData.Remarks = record[2]
          postData.DictionaryCategoryId = that.dictCategoryId
          var response = await apolloClient.mutate({
            mutation: gql`mutation ($req: DictAddReq!) {
                            dictAdd(Req: $req)
                        }`,
            variables: { req: postData }
          })
          if (!response.data) {
            that.$notify.error(response.errors[0].message)
          }
        }
        that.$notify.success('导入完成')
        that.research()
        loading.close()
      }
    },
    toAdd() {
      this.$router.push(`/dict/add/${this.dictCategoryId}`)
    },
    toDownloadTemplate() {
      location.href = './模板.csv'
    },
    toImport() {
      this.importDictDialog.show = true
    },
    toEdit(row) {
      console.log(row)
      this.$router.push(`/dict/edit/${row.DictionaryId}`)
    },
    toDel(row) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apolloClient.mutate({
          mutation: gql`mutation($unionId:String!){
                    dictDelete(dictId: $unionId)
                }`,
          variables: { unionId: row.DictionaryId }
        }).then(response => {
          if (response.data) {
            this.$notify.success('操作成功')
            this.research()
          } else {
            this.$notify.error(response.errors[0].message)
          }
        }).catch((err) => {
          this.$notify.error(err.message)
        })
      })
    },
    search() {
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query ($req: DictPageReq!) {
                    dictPage(Req: $req){
                        TotalRecord
                        Records{
                            DictionaryCategoryId
                            DictionaryId
                            Name
                            Value
                            Remarks
                            UpdatedAt
                            CreatedAt
                        }
                    }
                }`,
        variables: { req: this.queryParam }
      }).then(response => {
        console.log(response)
        var responseData = response.data
        this.data = responseData.dictPage.Records
        this.TotalRecord = responseData.dictPage.TotalRecord
      })
    },

    // 处理每页大小改变
    handleSizeChange(val) {
      this.queryParam.PageSize = val
      this.search()
    },
    // 处理页数改变
    handleCurrentChange(val) {
      this.queryParam.CurrentPage = val
      this.search()
    },
    // 重置分页条件，发起查询
    research() {
      this.queryParam.CurrentPage = 1
      this.search()
    }

  }
}
</script>

<style>
#app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
